/****************************************************************************
*  Arthea Server by R. Jennings (2007-2008)   http://arthea.googlecode.com/ *
*  By using this code you comply with the Artistic and GPLv2 Licenses.      *
****************************************************************************/


using System.Text;
using Arthea.Connections;
using Arthea.Connections.Players;

namespace Arthea.Util
{
    /// <summary>
    /// Handles displaying text in columns
    /// </summary>
    public struct Columns
    {
        /// <summary>
        /// The default width for a column
        /// </summary>
        public static readonly ushort DefaultWidth = 80;


        /// <summary>
        /// Gets the width of the player default.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="columns">The columns.</param>
        /// <returns></returns>
        public static ushort GetPlayerDefaultWidth(Player player, ushort columns)
        {
            return (ushort) ((player.Connection.Flags.Has(ConnectionFlags.NAWS)
                                  ? player.ScreenWidth
                                  : DefaultWidth)/columns);
        }

        /// <summary>
        /// Shows the specified player.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="objects">The objects.</param>
        public static void Show(Player player, ushort columns, params object[] objects)
        {
            Show(player, columns, GetPlayerDefaultWidth(player, columns), objects);
        }

        /// <summary>
        /// Displays a list of objects in columns
        /// </summary>
        /// <param name="player">the player viewing the columns</param>
        /// <param name="columns">the number of columns</param>
        /// <param name="width">the width of a column</param>
        /// <param name="objects">the list of objects to display in the columns as an array</param>
        public static void Show(Player player, ushort columns, ushort width, params object[] objects)
        {
            StringBuilder buf = new StringBuilder();

            for (int i = 0; i < objects.Length;)
            {
                String text = objects[i].ToString();

                string format = string.Format("{{0,-{0}}}", width + (text.Length - text.DisplayLength));

                buf.AppendFormat(format, text);

                ++i;

                if (text.DisplayLength >= width || (i%columns) == 0 || i == objects.Length)
                {
                    buf.AppendLine();
                }
            }

            player.SendPage(buf);
        }
    }
}